package com.zhangfuxing.datatools.core;

import com.zhangfuxing.datatools.logger.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author 张福兴
 * @version 1.0
 * @date 2024/10/2
 * @email zhangfuxing1010@163.com
 */
public class CommandReader {
    public static Runnable inputTips = () -> System.out.print(">>$ ");
    private final BufferedReader br;

    public CommandReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    public String readLine() throws IOException {
        inputTips.run();
        String line = br.readLine();
        if (line == null) {
            return readLine();
        }
        line = line.trim().toLowerCase();
        Command command = Command.parse(line);
        if (command == null) {
            Log.info("输入的命令无效，输入 /help 获取帮助。");
            return readLine();
        }
        try {
            command.execute();
        } catch (Exception e) {
            return readLine();
        }
        return line;
    }

    public String readAll() throws IOException {
        StringBuilder sb = new StringBuilder();
        while (true) {
            String line = readLine();
            if (line == null) {
                continue;
            }
            String lineLower = line.trim().toLowerCase();
            Command command = Command.parse(lineLower);
            if (command == null) {
                return this.readAll();
            }
            sb.append(line).append("\n");
            if (line.endsWith(";")) {
                break;
            }
        }
        return sb.toString();
    }
}
